

import nw from "nw-lafjs";
import {fail, ok} from "@/utils/responseUtil";
import cloud from "@lafjs/cloud";
const db = cloud.database()
const _ = db.command

export default async function (ctx: FunctionContext) {
  let body = ctx.body
  /**
   * {
   *   "userId": "wuh",
   *   "roleIds": ["1","2"]
   * }
   */

  //1.参数校验
  if (nw.util.isNull(body.userId)){
    return fail("用户不能为空")
  }
  if (!nw.util.isArray(body.roleIds)){
    return  fail("请选择需要赋予的角色")
  }
  //2.构建参数，保存数据
  let adminRoles = []
  for (let i = 0; i < body.roleIds.length; i++) {
    let adminRole = {
      roleId:body.roleIds[i],
      adminId:body.userId,
      createTime:new Date(),
      updateTime:new Date(),
      deleted:0
    }
    adminRoles[i]=adminRole
  }
  //清楚原有角色信息
  await nw.db.update({
    dbName:"adminRole",
    whereJson:{adminId:_.eq(body.userId)},
    dataJson:{deleted:1}
  })

  if (adminRoles.length===0){
    return ok("保存成功")
  }

  let numer = await db.collection("adminRole").add(adminRoles,{multi:true})
  if (!numer.ok){
    return fail("授权失败")
  }
  return ok("保存成功")

}
